import Vue from 'vue'
import { getAccessToken } from '@/utils/auth'
export default class WebSocketManager {
  static instance = null
  static eventBus = new Vue()
  static url = process.env.VUE_APP_BASE_API + "/infra/ws"
  constructor(url) {
    this.url = this.buildUrl(url)
    this.reconnectCount = 0
    this.maxReconnect = 5
    this.ws = null
  }

  // 构建带 Token 的 URL
  buildUrl(baseUrl) {
    const url = new URL(baseUrl.replace(/^http/, 'ws'))
    url.searchParams.set('token', getAccessToken())
    return url.toString()
  }

  connect() {
    if (this.ws) return

    this.ws = new WebSocket(this.url)
    this.bindEvents()
  }

  bindEvents() {
    this.ws.onopen = () => {
      this.reconnectCount = 0
      this.startHeartbeat()
    //   this.eventBus.$emit('connected')
    }

  this.ws.onmessage = (e) => {
  try {
    const msg = JSON.parse(e.data)
    console.log("收到原始消息:", msg)  // 更规范的日志输出
    if (msg.type === 'RentAdjustAudit') {  // 针对具体业务类型处理
      console.log('租金审批更新', msg.content)
          // 通过 Vuex 处理消息
    store.dispatch('websocket/handleWebSocketMessage', msg)
    }
    this.eventBus.$emit(msg.type || 'message', {
      ...msg,
      timestamp: new Date().getTime()  // 添加时间戳
    })
  } catch (error) {
    // console.error('消息解析失败', e.data, error)
    // this.eventBus.$emit('parse-error', { 
    //   rawData: e.data,
    //   error: error.message
    // })
  }
}


    this.ws.onclose = (e) => {
      if (!e.wasClean) this.handleReconnect()
    }
  }

  handleReconnect() {
    if (this.reconnectCount++ < this.maxReconnect) {
      setTimeout(() => this.connect(), Math.min(2000 * Math.pow(2, this.reconnectCount), 30000))
    }
  }

  startHeartbeat() {
    this.heartbeatTimer = setInterval(() => {
      if (this.isConnected) this.send('ping')
    }, 30000)
  }

  send(data) {
    if (this.isConnected) {
      this.ws.send(JSON.stringify(data))
    }
  }

  get isConnected() {
    return this.ws?.readyState === WebSocket.OPEN
  }

  static getInstance(url) {
    if (!this.instance) {
      this.instance = new WebSocketManager(url)
    }
    return this.instance
  }
}